package com.cntv.viewmodeldemo.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.annotation.Nullable
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import com.cntv.viewmodeldemo.R
import kotlinx.android.synthetic.main.fragment_bottom.*


class BottomFragment : Fragment() {
//    private lateinit var mModel: UserModel

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_bottom, container, false)
    }

    override fun onViewCreated(view: View, @Nullable savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        val mModel = ViewModelProvider(requireActivity()).get(UserModel::class.java)
//       val mModel = activity?.let { ViewModelProvider(it).get(UserModel::class.java) }!!
        val mModel: UserModel by activityViewModels()//      X  val mModel: UserModel by viewModels()


//        mModel.getUser()?.observe(viewLifecycleOwner,Observer{
//                fragment_text_view.text=UserModel.getFormatContent(it.name,
//                    it.phone,
//                    it.address)
//
//        })
        /**
        *这里 observe 和上面不同。这里是livedata-ktx扩展提供的。对比上面，下面就是使用kotlin语言特性的写法
        */
        mModel.getUser()?.observe(viewLifecycleOwner){user->
            fragment_text_view.text=UserModel.getFormatContent(user.name,
                user.phone,
                user.address)
        }

    }
}